<template>
  <div
    :class="['shape-box']"
    :style="style"
    @mousedown.stop="handleMousedown"
    ref="shapeboxRef"
  >
    <slot></slot>
    <div
      v-show="selectedComponent.id == element.id"
      class="selected-line"
    ></div>
  </div>
</template>

<script setup>
import { computed, onBeforeUnmount, ref, watch } from "vue"
import store from "@/store"

let props = defineProps({
  // 形状
  element: {
    type: Object,
    default: () => {},
    required: true,
  },
  index: {
    type: Number,
    default: 0,
  },
})

let shapeboxRef = ref()
let style = computed(() => {
  let attr = props.element.attr ?? {}
  return {
    width: attr.w + "px",
    height: attr.h + "px",
    left: attr.x + "px",
    top: attr.y + "px",
    zIndex: attr.zIndex,
  }
})
let selectedComponent = computed(() => {
  return store.state.chartEditStore.selectedComponent || {}
})
let canvasConfig = computed(() => {
  return store.state.chartEditStore.editCanvasConfig
})
let canvasPosition = computed(() => {
  return store.state.chartEditStore.canvasPosition
})
let scale = computed(() => {
  return store.state.chartEditStore.editCanvas.scale
})

let startPoint = {
  x: 0,
  y: 0,
}

function handleMousedown(e) {
  let { offsetX, offsetY } = e
  startPoint.x = offsetX
  startPoint.y = offsetY
  store.commit("chartEditStore/SET_SELECTCOMPONENT", props.element)
  store.commit("chartEditStore/SET_EDITCANVAS", { isDrag: true })
  store.commit("chartEditStore/SET_SELECT_ELEMENT", shapeboxRef.value)
  document.addEventListener("mousemove", handleMousemove)
  document.addEventListener("mouseup", handleMouseup)
}
function handleMouseup() {
  store.commit("chartEditStore/ADD_HISTORY")
  removeListen()
}

function handleMousemove(e) {
  let { pageX, pageY } = e
  let { x, y } = canvasPosition.value
  props.element.attr.x = (pageX - x) / (scale.value / 100) - startPoint.x
  props.element.attr.y = (pageY - y) / (scale.value / 100) - startPoint.y
  props.element.attr.right =
    canvasConfig.value.width - props.element.attr.w - props.element.attr.x
  props.element.attr.bottom =
    canvasConfig.value.height - props.element.attr.h - props.element.attr.y
}

function removeListen() {
  document.removeEventListener("mousemove", handleMousemove)
  document.removeEventListener("mouseup", handleMouseup)
  store.commit("chartEditStore/SET_EDITCANVAS", { isDrag: false })
}

onBeforeUnmount(() => {
  removeListen()
})
</script>

<style lang="scss" scoped>
.shape-box {
  position: absolute;
}
.selected-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 2px solid #15f47d;
  box-shadow: 0 0 2px 2px #15f47d;
  pointer-events: none;
}
</style>
